<template>
  <div class="update-name">
      <van-nav-bar
        title="修改呢称"
        left-text="取消"
        right-text="确定"
        @click-left="$emit('close')"
        @click-right="onComfirm"
      ></van-nav-bar>
      <div class="name-field-wrap">
        <van-field
            v-model.trim="localName"
            rows="2"
            autosize
            type="textarea"
            maxlength="7"
            show-word-limit
        />
      </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user'

export default {
  name: 'UpdateName',
  components: {},
  props: {
      // 父组件 v-model 传递过来的值
      value: {
          type: String,
          require: true
      }
  },
  data() {
    return {
        localName: this.value // 呢称
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
      async onComfirm() {
          this.$toast.loading({
              message: '保存中',
              forbidClick: true
          })

          try {
              await updateUserProfile({
                  name: this.localName
              })
              // 返回给父组件 v-model 监听数据变化
              this.$emit('input', this.localName)
              this.$emit('close')
              this.$toast.success('保存成功')
          } catch (err) {
              if( err && err.response && err.response.status === 409) {
                  this.$toast.fail('呢称已存在')
              }
          }
      }
  }
};
</script>
<style lang="less" scoped>
.name-field-wrap {
    padding: 10px;
}
</style>